<script setup lang="ts">
import { ref, onMounted, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { Message, Modal } from '@arco-design/web-vue'
import { useMerchantStore } from '@/stores/merchant'
import { getMerchantOrders, acceptOrder, completeOrder, type Order, type PageData } from '@/api/order'
import type { ApiResponse } from '@/api/user'

const router = useRouter()
const merchantStore = useMerchantStore()
const loading = ref(false)
const orders = ref<Order[]>([])
const actionLoading = reactive<Record<string, boolean>>({})

// 分页信息
const pagination = reactive({
  total: 0,
  current: 1,
  pageSize: 10
})

// 订单状态映射
const orderStatusMap: Record<number, { text: string; color: string }> = {
  0: { text: '待支付', color: '#ff7d00' },
  1: { text: '已支付', color: '#3c7eff' },
  2: { text: '商家已接单', color: '#00b42a' },
  3: { text: '配送中', color: '#7bc616' },
  4: { text: '已完成', color: '#86909c' },
  5: { text: '已取消', color: '#f53f3f' }
}

// 初始化数据
onMounted(async () => {
  loading.value = true
  try {
    // 如果store中没有商家信息，则获取
    if (!merchantStore.currentMerchant) {
      await merchantStore.fetchCurrentMerchant()
    }
    
    // 如果获取失败或仍然没有商家信息，跳转到登录页
    if (!merchantStore.currentMerchant) {
      throw new Error('获取商家信息失败')
    }
    
    // 加载订单数据
    await fetchOrders()
    
  } catch (error) {
    console.error('初始化失败:', error)
    Message.error('初始化失败，请稍后再试')
    
    // 如果获取商家信息失败，可能是token无效，跳转到登录页
    router.push('/merchant/login')
  } finally {
    loading.value = false
  }
})

// 获取商家订单
const fetchOrders = async () => {
  try {
    if (!merchantStore.currentMerchant?.id) return
    
    const res = await getMerchantOrders(merchantStore.currentMerchant.id)
    if (res.code === 0 || res.code === 200) {
      // 处理分页数据结构
      if (res.data) {
        const pageData = res.data as PageData<Order>
        if (pageData.content) {
          orders.value = pageData.content
          pagination.total = pageData.totalElements || 0
          pagination.current = (pageData.number || 0) + 1
          pagination.pageSize = pageData.size || 10
        } else {
          orders.value = []
        }
      } else {
        orders.value = []
      }
    } else {
      Message.error(res.message || '获取订单列表失败')
    }
  } catch (error) {
    console.error('获取订单列表失败:', error)
    Message.error('获取订单列表失败，请稍后再试')
  }
}

// 接单
const handleAcceptOrder = async (order: Order) => {
  if (!order.orderNo) return
  
  actionLoading[order.orderNo] = true
  try {
    const res = await acceptOrder(order.orderNo)
    if (res.code === 0 || res.code === 200) {
      Message.success('接单成功')
      await fetchOrders() // 刷新订单列表
    } else {
      Message.error(res.message || '接单失败')
    }
  } catch (error) {
    console.error('接单失败:', error)
    Message.error('接单失败，请稍后再试')
  } finally {
    actionLoading[order.orderNo] = false
  }
}

// 完成订单
const handleCompleteOrder = async (order: Order) => {
  if (!order.orderNo) return
  
  Modal.confirm({
    title: '确认完成订单',
    content: `确定要将订单 ${order.orderNo} 标记为已完成吗？`,
    okText: '确认',
    cancelText: '取消',
    onOk: async () => {
      actionLoading[order.orderNo!] = true
      try {
        const res = await completeOrder(order.orderNo!)
        if (res.code === 0 || res.code === 200) {
          Message.success('订单已完成')
          await fetchOrders() // 刷新订单列表
        } else {
          Message.error(res.message || '操作失败')
        }
      } catch (error) {
        console.error('完成订单失败:', error)
        Message.error('操作失败，请稍后再试')
      } finally {
        actionLoading[order.orderNo!] = false
      }
    }
  })
}

// 返回商家管理中心
const goToDashboard = () => {
  router.push('/merchant/dashboard')
}

// 格式化时间
const formatTime = (time: string | undefined) => {
  if (!time) return '-'
  return new Date(time).toLocaleString()
}

// 刷新订单列表
const refreshOrders = async () => {
  loading.value = true
  try {
    await fetchOrders()
    Message.success('刷新成功')
  } catch (error) {
    console.error('刷新失败:', error)
    Message.error('刷新失败，请稍后再试')
  } finally {
    loading.value = false
  }
}
</script>

<template>
  <div class="merchant-orders-container">
    <a-spin :loading="loading" tip="加载中...">
      <!-- 标题栏 -->
      <div class="orders-header">
        <a-button shape="circle" @click="goToDashboard">
          <template #icon><icon-left /></template>
        </a-button>
        <h2>订单管理</h2>
        <a-button type="primary" @click="refreshOrders">
          <template #icon><icon-refresh /></template>
          刷新
        </a-button>
      </div>

      <div class="orders-content">
        <template v-if="orders.length > 0">
          <div class="orders-list">
            <a-card v-for="order in orders" :key="order.id" class="order-card">
              <div class="order-header">
                <div class="order-no">订单号：{{ order.orderNo }}</div>
                <div class="order-status" :style="{ color: orderStatusMap[order.status || 0]?.color }">
                  {{ order.statusDesc || orderStatusMap[order.status || 0]?.text }}
                </div>
              </div>
              
              <div class="order-info">
                <div class="info-item">
                  <span class="label">下单时间：</span>
                  <span>{{ formatTime(order.createTime) }}</span>
                </div>
                <div class="info-item">
                  <span class="label">收货人：</span>
                  <span>{{ order.receiverName }}</span>
                </div>
                <div class="info-item">
                  <span class="label">联系电话：</span>
                  <span>{{ order.receiverPhone }}</span>
                </div>
                <div class="info-item">
                  <span class="label">收货地址：</span>
                  <span>{{ order.deliveryAddress }}</span>
                </div>
                <div class="info-item" v-if="order.remark">
                  <span class="label">备注：</span>
                  <span>{{ order.remark }}</span>
                </div>
              </div>
              
              <a-divider />
              
              <div class="order-items" v-if="order.orderItems && order.orderItems.length > 0">
                <div v-for="item in order.orderItems" :key="item.id" class="order-item">
                  <div class="item-image" v-if="item.dishImage">
                    <img :src="item.dishImage" :alt="item.dishName" />
                  </div>
                  <div class="item-info">
                    <div class="item-name">{{ item.dishName }}</div>
                    <div class="item-price">¥{{ item.dishPrice }}</div>
                  </div>
                  <div class="item-quantity">x{{ item.quantity }}</div>
                </div>
              </div>
              <div v-else class="no-items">暂无菜品详情</div>
              
              <a-divider />
              
              <div class="order-footer">
                <div class="order-amount">
                  <span>实付金额：</span>
                  <span class="amount">¥{{ order.actualAmount }}</span>
                </div>
                <div class="order-actions">
                  <a-button 
                    v-if="order.status === 1" 
                    type="primary" 
                    @click="handleAcceptOrder(order)"
                    :loading="actionLoading[order.orderNo || '']"
                  >
                    接单
                  </a-button>
                  <a-button 
                    v-if="order.status === 2" 
                    type="primary" 
                    status="success" 
                    @click="handleCompleteOrder(order)"
                    :loading="actionLoading[order.orderNo || '']"
                  >
                    完成订单
                  </a-button>
                </div>
              </div>
            </a-card>
          </div>
          
          <div class="pagination" v-if="pagination.total > pagination.pageSize">
            <a-pagination
              v-model:current="pagination.current"
              :total="pagination.total"
              :page-size="pagination.pageSize"
              @change="fetchOrders"
            />
          </div>
        </template>
        <a-empty v-else description="暂无订单数据" />
      </div>
    </a-spin>
  </div>
</template>

<style scoped>
.merchant-orders-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
  width: 100%;
}

.orders-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 30px;
}

.orders-header h2 {
  margin: 0;
  font-size: 24px;
  color: var(--color-text-1);
}

.orders-content {
  background-color: var(--color-bg-2);
  border-radius: 12px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
  padding: 24px;
}

.orders-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.order-card {
  width: 100%;
  border-radius: 8px;
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.order-no {
  font-weight: 500;
  color: var(--color-text-1);
}

.order-status {
  font-weight: 500;
}

.order-info {
  margin-bottom: 16px;
}

.info-item {
  margin-bottom: 8px;
  display: flex;
}

.info-item .label {
  color: var(--color-text-3);
  width: 80px;
  flex-shrink: 0;
}

.order-items {
  margin-bottom: 16px;
}

.order-item {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
}

.item-image {
  width: 50px;
  height: 50px;
  border-radius: 4px;
  overflow: hidden;
  margin-right: 12px;
}

.item-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.item-info {
  flex: 1;
}

.item-name {
  font-weight: 500;
  margin-bottom: 4px;
}

.item-price {
  color: var(--color-text-3);
  font-size: 14px;
}

.item-quantity {
  color: var(--color-text-2);
  margin-left: 12px;
}

.order-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.order-amount {
  font-size: 16px;
}

.order-amount .amount {
  font-weight: 600;
  color: #ff7d00;
}

.order-actions {
  display: flex;
  gap: 12px;
}

.no-items {
  color: var(--color-text-3);
  font-style: italic;
  text-align: center;
  padding: 10px 0;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

/* 响应式布局 */
@media (max-width: 768px) {
  .merchant-orders-container {
    padding: 16px;
  }
  
  .orders-content {
    padding: 16px;
  }
  
  .order-footer {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
  
  .order-actions {
    width: 100%;
    justify-content: flex-end;
  }
}
</style> 